package com.yc.io.netty.demo2;

import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyClientHandler extends ChannelInboundHandlerAdapter {

	private static final Logger logger = Logger.getLogger(MyClientHandler.class.getName());

	/**
	 * 服务器和客户端连接成功后
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		String res = "我是客户端" + Thread.currentThread().getName();
		byte[] reqbyte = res.getBytes("utf-8");
		ByteBuf bb = Unpooled.buffer(reqbyte.length);
		bb.writeBytes(reqbyte);//写到缓冲区
		ctx.writeAndFlush(bb);//发送给服务器
	}

	/**
	 * 服务器应答之后调用
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] bt = new byte[buf.readableBytes()];
		buf.readBytes(bt);
		String body = new String(bt, "utf-8");
		System.out.println(Thread.currentThread().getName() + ", server return message:" + body);
		ctx.close();
		
	}

	/**
	 * 发生异常，打印异常日志，关闭资源
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warning("client have something wrong: " + cause.getMessage());
		ctx.close();
	}
	
	
}
